package controllers

import (
	"auusoft/AuuWiki/Models"
	//"fmt"
	"github.com/astaxie/beego"
)

type RootController struct {
	beego.Controller
}

type MainController struct {
	RootController
}

func (this *MainController) Get() {
	sess := this.StartSession()
	username := sess.Get("username")
	if username != nil {
		this.Data["username"] = username
	} else {
		this.Ctx.Redirect(302, "/login")
	}

	this.Ctx.Request.ParseForm()
	title := this.Ctx.Request.Form.Get("wiki")
	if title == "" {
		title = `一切从这里开始`
	}
	if title != "" {
		wikis, _ := models.GetWikiByTitle(title)
		if len(wikis) > 0 {
			this.Data["title"] = title
			content := wikis[0].Content
			content = ReplaceHtml(content)
			content = ConvertFromWikiToHtml(content)
			t1 := beego.MarkDown(content)
			this.Data["content"] = t1
			this.Data["log"] = beego.MarkDown(wikis[0].Log)[3 : len(beego.MarkDown(wikis[0].Log))-5]
			this.Data["edittitle"] = title
		} else {
			this.Ctx.Redirect(302, "/edit/?wiki="+title)
		}
	}

	//处理浏览列表
	mylist := ""

	list1 := sess.Get("mylist")

	if list1 != nil {
		listslice := list1.([]string)

		if len(listslice) > 0 {
			if !Contains(listslice, title) {
				listslice = append(listslice, title)
			} else {
				listslice = RemoveFromSlice(listslice, title)
				listslice = append(listslice, title)
			}

			for _, line := range listslice {
				mylist = `<li><a href="/?wiki=` + line + `">` + line + `</a></li>` + mylist
			}
			this.Data["mylist"] = beego.MarkDown(mylist)
		}

		//保证浏览列表最大数量不多于listnumber参数
		listnum, _ := beego.AppConfig.Int("listnumber")
		if len(listslice) > listnum {
			listslice = listslice[1:]
		}

		sess.Set("mylist", listslice)
	} else {
		listslice := []string{title}
		sess.Set("mylist", listslice)
	}

	this.Layout = "layout.html"
	this.TplNames = "Index.html"

}

func Contains(list []string, elem string) bool {
	for _, t := range list {
		if t == elem {
			return true
		}
	}
	return false
}

func RemoveFromSlice(list []string, elem string) []string {
	j := -1
	for i, t := range list {
		if t == elem {
			j = i
			break
		}
	}
	if j == 0 {
		list = list[1:]
	} else if j > 0 {
		list = append(list[:j], list[j+1:]...)
	}

	return list
}

func (this *RootController) CheckSession() interface{} {
	sess := this.StartSession()
	if sess.Get("username") == nil {
		this.Ctx.Redirect(302, "/login")
	}

	return sess.Get("username")
}
